#!/usr/bin/env ruby

#
# Implements xmlrpc exporting and sampling for simmon. Noteworthy issues:
#
# * We base64 the marshalled objects; the xmlrpc library or protocol seems
#   to mangle binary data.
#

require 'base64'
require 'xmlrpc/client'
require 'xmlrpc/server'

require 'simmon/sensor'

module Simmon
  class XmlrpcSensor < Sensor
    def initialize(remotename,
                   host,
                   port,
                   interval = 60,
                   maxlag = interval * 2,
                   initial_state = State.new(true))
      super("#{remotename}@#{host}", interval, maxlag, initial_state)
      
      @remotename = remotename
      @host = host
      @port = port
      @server = XMLRPC::Client.new(@host, "/", @port)
    end

    def sample()
      Marshal.load(Base64.decode64(@server.call("simmon.sample_sensor", @remotename)))
    end
  end

  class XmlrpcExporter
    def initialize(port)
      @sensors = Hash.new()
      @server = XMLRPC::Server.new(port)
      @server.add_handler("simmon.sample_sensor") do |name|
        Base64.encode64(Marshal.dump(self.sample_sensor(name)))
      end
      trap('INT') { @server.shutdown }
      trap('TERM') { @server.shutdown }
    end
    
    def start()
      @server.serve()
    end
    
    def register_sensor(sensor)
      @sensors[sensor.name()] = sensor
    end
    
    def sample_sensor(name)
      sensor = @sensors[name]
      
      if sensor then
        return sensor.state()
      else
        return State.new(false, nil, "sensor #{name} does not exist")
      end
    end
  end
end
